package thread;

import java.util.Scanner;

public class Demo6_valatile {
//    private static int flag = 0;
    private volatile static int flag = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            while(flag == 0){
                // do nothing...

//                try {
//                    Thread.sleep(1);
                // sleep thread switch CPU context, and then read from main memory not work memory
                // Sleeping may trigger a context switch, which sometimes causes the thread
                // to observe updated values. However, Thread.sleep() DOES NOT guarantee
                // visibility under the Java Memory Model. Use volatile/synchronized instead.
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
            }
            System.out.println("flag is not equals to 0");
        });
        Thread t2 = new Thread(()->{
            Scanner scan = new Scanner(System.in);
            flag = scan.nextInt();
        });
        t1.start();
        t2.start();
        t1.join();
    }
}
